<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @closed="resetForm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      status-icon
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户名称" :disabled="type === 'view'" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入用户昵称" :disabled="type === 'view'" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="form.deptId"
          :data="deptOptions"
          placeholder="请选择部门"
          :disabled="type === 'view'"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" placeholder="请输入手机号码" :disabled="type === 'view'" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="type === 'view'" />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-radio-group v-model="form.sex" :disabled="type === 'view'">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
          <el-radio label="2">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" :disabled="type === 'view'">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="type !== 'view'" label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="form.roleIds"
          multiple
          placeholder="请选择角色"
          style="width: 100%"
          :disabled="type === 'view'"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :disabled="type === 'view'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button v-if="type !== 'view'" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add' // add, edit, view
  },
  userData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'success', 'cancel']);

// 表单引用
const formRef = ref<FormInstance>();

// 部门选项
const deptOptions = ref([
  { 
    id: 1, 
    label: '总公司', 
    children: [
      { id: 2, label: '技术部' },
      { id: 3, label: '市场部' },
      { id: 4, label: '财务部' }
    ] 
  }
]);

// 角色选项
const roleOptions = ref([
  { label: '管理员', value: 1 },
  { label: '普通用户', value: 2 },
  { label: '游客', value: 3 }
]);

// 表单数据
const form = ref({
  userId: undefined,
  userName: '',
  nickName: '',
  deptId: undefined,
  phonenumber: '',
  email: '',
  sex: '0',
  status: '0',
  password: '',
  roleIds: [],
  remark: ''
});

// 表单验证规则
const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: props.type === 'add', message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
});

// 标题
const title = computed(() => {
  if (props.type === 'add') return '添加用户';
  if (props.type === 'edit') return '编辑用户';
  return '查看用户';
});

// 监听用户数据变化
watch(() => props.userData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    form.value = { ...form.value, ...newValue };
  }
}, { deep: true });

// 监听表单类型
watch(() => props.type, (newType) => {
  // 当类型为编辑时，移除密码必填验证
  if (newType === 'edit') {
    rules.password = [
      { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ];
  } else if (newType === 'add') {
    rules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ];
  }
}, { immediate: true });

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
};

// 重置表单
const resetForm = () => {
  form.value = {
    userId: undefined,
    userName: '',
    nickName: '',
    deptId: undefined,
    phonenumber: '',
    email: '',
    sex: '0',
    status: '0',
    password: '',
    roleIds: [],
    remark: ''
  };
  formRef.value?.resetFields();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate((valid) => {
    if (valid) {
      // 调用API提交表单
      const isAdd = props.type === 'add';
      const successMsg = isAdd ? '添加成功' : '修改成功';
      
      setTimeout(() => {
        ElMessage.success(successMsg);
        emit('update:visible', false);
        emit('success', form.value);
      }, 300);
    }
  });
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 